package sv.gob.mtps.sib.controller;
 

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import sv.gob.mtps.sib.model.Proveedor;
import sv.gob.mtps.sib.service.ProveedorService;
 
@Controller
public class ProveedorController {
	
	@Autowired
    private ProveedorService proveedorService;
	
	@RequestMapping("/admin/proveedor")
    public String listProveedores(Map<String, Object> map) {
			map.put("proveedor", new Proveedor());
			map.put("proveedorList", proveedorService.listProveedor());		
        return "/admin/proveedor";
    }
 
	@RequestMapping(value = "/admin/proveedor/add", method = RequestMethod.POST)
    public String addProveedor(@ModelAttribute("proveedor") Proveedor proveedor, BindingResult result) { 
		try{
			proveedorService.addProveedor(proveedor);
		}
		catch(DataAccessException ex){
			ex.printStackTrace();
		}         
        return "redirect:/admin/proveedor";
    }
	
	@RequestMapping(value = "/admin/proveedor/edit", method = RequestMethod.POST)
	public String editProveedor(@ModelAttribute("proveedor") Proveedor proveedor, BindingResult result){
		try{
			proveedorService.updateProveedor(proveedor);
		}
		catch(DataAccessException ex){
			ex.printStackTrace();
		}
		
			return "redirect:/admin/proveedor";
	}
	
	@RequestMapping(value ="/admin/proveedor/delete", method = RequestMethod.POST)
	public String deleteProveedor(@ModelAttribute("proveedor") Proveedor proveedor, BindingResult result){
		try{
			proveedorService.removeProveedor(proveedor.getIdProveedor());
		}
		catch(DataAccessException ex){
			ex.printStackTrace();
		}
		 
        return "redirect:/admin/proveedor";
    }

}
